// Package expressinfo
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2025 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
// @AutoGenerate Version 2.15.11
package expressinfo

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/os/gtime"
	"hotgo/internal/consts"
	"hotgo/internal/dao"
	"hotgo/internal/library/contexts"
	"hotgo/internal/library/hfsm"
	"hotgo/internal/library/hgorm"
	"hotgo/internal/library/hgorm/handler"
	"hotgo/internal/model"
	"hotgo/internal/model/input/expressinfoin"
	"hotgo/internal/model/input/form"
	"hotgo/internal/service"
	"hotgo/utility/convert"
	"hotgo/utility/excel"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/util/gconv"
)

type sExpressinfoExpressInfo struct{}

func NewExpressinfoExpressInfo() *sExpressinfoExpressInfo {
	return &sExpressinfoExpressInfo{}
}

func init() {
	service.RegisterExpressinfoExpressInfo(NewExpressinfoExpressInfo())
}

// Model 物流信息ORM模型
func (s *sExpressinfoExpressInfo) Model(ctx context.Context, option ...*handler.Option) *gdb.Model {
	return handler.Model(dao.ExpressInfo.Ctx(ctx), option...)
}

// List 获取物流信息列表
func (s *sExpressinfoExpressInfo) List(ctx context.Context, in *expressinfoin.ExpressInfoListInp) (list []*expressinfoin.ExpressInfoListModel, totalCount int, err error) {
	mod := s.Model(ctx)

	// 字段过滤
	mod = mod.FieldsPrefix(dao.ExpressInfo.Table(), expressinfoin.ExpressInfoListModel{})
	mod = mod.Fields(hgorm.JoinFields(ctx, expressinfoin.ExpressInfoListModel{}, &dao.Order, "order"))
	//mod = mod.Fields(hgorm.JoinFields(ctx, expressinfoin.ExpressInfoListModel{}, &dao.Store, "store"))
	mod = mod.Fields(hgorm.JoinFields(ctx, expressinfoin.ExpressInfoListModel{}, &dao.Product, "product"))
	mod = mod.Fields(hgorm.JoinFields(ctx, expressinfoin.ExpressInfoListModel{}, &dao.AdminMember, "adminMember"))
	mod = mod.Fields()

	// 关联表字段
	mod = mod.LeftJoinOnFields(dao.Order.Table(), dao.ExpressInfo.Columns().OrderUid, "=", dao.Order.Columns().Uid)
	//mod = mod.LeftJoinOnFields(dao.Store.Table(), dao.ExpressInfo.Columns().StoreId, "=", dao.Store.Columns().Id)
	mod = mod.LeftJoinOnFields(dao.Product.Table(), dao.ExpressInfo.Columns().ProductId, "=", dao.Product.Columns().Id)
	mod = mod.LeftJoinOnFields(dao.AdminMember.Table(), dao.ExpressInfo.Columns().OperatorId, "=", dao.AdminMember.Columns().Id)

	// 查询id
	if in.Id > 0 {
		mod = mod.Where(dao.ExpressInfo.Columns().Id, in.Id)
	}

	// 查询订单uid
	if in.OrderUid != "" {
		mod = mod.WhereLike(dao.ExpressInfo.Columns().OrderUid, "%"+in.OrderUid+"%")
	}

	// 查询购买者id
	if in.UserId > 0 {
		mod = mod.Where(dao.ExpressInfo.Columns().UserId, in.UserId)
	}

	// 查询状态
	if in.Status > 0 {
		mod = mod.Where(dao.ExpressInfo.Columns().Status, in.Status)
	}

	// 查询快递单号
	if in.ExpressNumber != "" {
		mod = mod.WhereLike(dao.ExpressInfo.Columns().ExpressNumber, "%"+in.ExpressNumber+"%")
	}

	// 查询创建时间
	if len(in.CreatedAt) == 2 {
		mod = mod.WhereBetween(dao.ExpressInfo.Columns().CreatedAt, in.CreatedAt[0], in.CreatedAt[1])
	}

	// 分页
	mod = mod.Page(in.Page, in.PerPage)

	// 排序
	mod = mod.OrderDesc(dao.ExpressInfo.Table() + "." + dao.ExpressInfo.Columns().Id)

	// 查询数据
	if err = mod.ScanAndCount(&list, &totalCount, false); err != nil {
		err = gerror.Wrap(err, "获取物流信息列表失败，请稍后重试！")
		return
	}
	return
}

// Export 导出物流信息
func (s *sExpressinfoExpressInfo) Export(ctx context.Context, in *expressinfoin.ExpressInfoListInp) (err error) {
	list, totalCount, err := s.List(ctx, in)
	if err != nil {
		return
	}

	// 字段的排序是依据tags的字段顺序，如果你不想使用默认的排序方式，可以直接定义 tags = []string{"字段名称", "字段名称2", ...}
	tags, err := convert.GetEntityDescTags(expressinfoin.ExpressInfoExportModel{})
	if err != nil {
		return
	}

	var (
		fileName  = "导出物流信息-" + gctx.CtxId(ctx)
		sheetName = fmt.Sprintf("索引条件共%v行,共%v页,当前导出是第%v页,本页共%v行", totalCount, form.CalPageCount(totalCount, in.PerPage), in.Page, len(list))
		exports   []expressinfoin.ExpressInfoExportModel
	)

	if err = gconv.Scan(list, &exports); err != nil {
		return
	}

	err = excel.ExportByStructs(ctx, tags, exports, fileName, sheetName)
	return
}

// Edit 修改/新增物流信息
func (s *sExpressinfoExpressInfo) Edit(ctx context.Context, in *expressinfoin.ExpressInfoEditInp) (id int64, err error) {
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {

		// 修改
		if in.Id > 0 {
			// 确认发货
			if in.IsConfirm {
				order, err2 := service.SysUserOrder().GetOrderByUID(ctx, in.OrderUid, 0)
				if err2 != nil {
					return err2
				}

				// 修改订单状态：待发货 -> 已发货
				if order.Status == consts.UserOrderStatusWaitExpress {
					err = hfsm.OFSM.PushState(order.Id, consts.WaitExpressToExpressedEvent)
					if err != nil {
						return gerror.New("操作失败")
					}

					in.OperatorId = contexts.GetUserId(ctx)
					in.DispatchTime = gtime.Now()
				}
			}

			id = int64(in.Id)
			if _, err = s.Model(ctx).
				Fields(expressinfoin.ExpressInfoUpdateFields{}).
				WherePri(in.Id).Data(in).OmitEmptyData().Update(); err != nil {
				err = gerror.Wrap(err, "修改物流信息失败，请稍后重试！")
			}

			return
		}

		// 新增
		id, err = s.Model(ctx, &handler.Option{FilterAuth: false}).
			Fields(expressinfoin.ExpressInfoInsertFields{}).
			Data(in).OmitEmptyData().InsertAndGetId()
		if err != nil {
			err = gerror.Wrap(err, "新增物流信息失败，请稍后重试！")
		}
		return
	})
	return
}

// Delete 删除物流信息
func (s *sExpressinfoExpressInfo) Delete(ctx context.Context, in *expressinfoin.ExpressInfoDeleteInp) (err error) {

	if _, err = s.Model(ctx).WherePri(in.Id).Unscoped().Delete(); err != nil {
		err = gerror.Wrap(err, "删除物流信息失败，请稍后重试！")
		return
	}
	return
}

// View 获取物流信息指定信息
func (s *sExpressinfoExpressInfo) View(ctx context.Context, in *expressinfoin.ExpressInfoViewInp) (res *expressinfoin.ExpressInfoViewModel, err error) {
	mod := s.Model(ctx)

	// 字段过滤
	mod = mod.FieldsPrefix(dao.ExpressInfo.Table(), expressinfoin.ExpressInfoViewModel{})
	mod = mod.Fields(hgorm.JoinFields(ctx, expressinfoin.ExpressInfoViewModel{}, &dao.Order, "order"))
	mod = mod.Fields(hgorm.JoinFields(ctx, expressinfoin.ExpressInfoViewModel{}, &dao.Store, "store"))
	mod = mod.Fields(hgorm.JoinFields(ctx, expressinfoin.ExpressInfoViewModel{}, &dao.Product, "product"))
	mod = mod.Fields(hgorm.JoinFields(ctx, expressinfoin.ExpressInfoViewModel{}, &dao.AdminMember, "adminMember"))
	mod = mod.Fields()

	// 关联表字段
	mod = mod.LeftJoinOnFields(dao.Order.Table(), dao.ExpressInfo.Columns().OrderUid, "=", dao.Order.Columns().Uid)
	mod = mod.LeftJoinOnFields(dao.Store.Table(), dao.ExpressInfo.Columns().StoreId, "=", dao.Store.Columns().Id)
	mod = mod.LeftJoinOnFields(dao.Product.Table(), dao.ExpressInfo.Columns().ProductId, "=", dao.Product.Columns().Id)
	mod = mod.LeftJoinOnFields(dao.AdminMember.Table(), dao.ExpressInfo.Columns().OperatorId, "=", dao.AdminMember.Columns().Id)

	if err = mod.WherePri(in.Id).Scan(&res); err != nil {
		err = gerror.Wrap(err, "获取物流信息信息，请稍后重试！")
		return
	}
	return
}

func (this *sExpressinfoExpressInfo) ToExpressed(ctx context.Context, in *expressinfoin.ExpressInfoChangeStatusInp, user *model.Identity) (err error) {
	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {
		if _, err = this.Model(ctx).
			Fields(expressinfoin.ExpressInfoUpdateFields{}).
			Where(dao.ExpressInfo.Columns().Id, in.Id).
			Data(g.Map{
				dao.ExpressInfo.Columns().Recipient:          in.Recipient,
				dao.ExpressInfo.Columns().Tel:                in.Tel,
				dao.ExpressInfo.Columns().ShippingProvinceId: in.ShippingProvinceId,
				dao.ExpressInfo.Columns().ShippingAddress:    in.ShippingAddress,
				dao.ExpressInfo.Columns().Status:             consts.ExpressStatusYes,
				dao.ExpressInfo.Columns().ExpressCompany:     in.ExpressCompany,
				dao.ExpressInfo.Columns().ExpressNumber:      in.ExpressNumber,
				dao.ExpressInfo.Columns().OperatorId:         user.Id,
				dao.ExpressInfo.Columns().DispatchTime:       gtime.Now().String(),
			}).Update(); err != nil {
			err = gerror.Wrap(err, "修改物流信息失败，请稍后重试！")
			return
		}
		expressInfo, err := this.View(ctx, &expressinfoin.ExpressInfoViewInp{Id: in.Id})
		if err != nil {
			return err
		}
		order, err := service.SysUserOrder().GetOrderByUID(ctx, expressInfo.OrderUid, 0)
		if err != nil {
			return err
		}
		hfsm.OFSM.PushState(order.Id, consts.WaitExpressToExpressedEvent)
		return
	})
}
